<?php

/**
 * 七牛相关控制器
 */

namespace app\common\file;

use app\BaseController;
use Qiniu\Auth;

class QiniuService extends BaseController
{
    /**
     * 获取七牛token
     *
     * @return void
     */
    public static function getToken()
    {
        $qiniu_access_key    = config('system.qiniu_access_key');
        $qiniu_access_secret = config('system.qiniu_access_secret');
        $qiniu_bucket        = config('system.qiniu_bucket');
        $auth = new Auth($qiniu_access_key, $qiniu_access_secret);
        $upToken = $auth->uploadToken($qiniu_bucket);
        return $upToken;
    }

    /**
     * 七牛图片文件上传
     *
     * @param [type] $file
     * @return void
     */
    public function Upload($file)
    {
        // 要上传图片的本地路径
        $filePath = $file->getRealPath();
        $ext = $file->getOriginalExtension;  //后缀
        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
        // 需要填写你的 Access Key 和 Secret Key
        $qiniu_access_key    = config('system.qiniu_access_key');
        $qiniu_access_secret = config('system.qiniu_access_secret');
        // 构建鉴权对象
        $auth = new Auth($qiniu_access_key, $qiniu_access_secret);
        // 要上传的空间
        $qiniu_bucket = config('system.qiniu_bucket');
        $token = $auth->uploadToken($qiniu_bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new \Qiniu\Storage\UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        if ($err !== null) {
            return false;
        } else {
            $domain = config('system.qiniu_domain');
            $data = 'http://' . $domain . '/' . $ret['key'];
            //返回图片的完整URL
            return $data;
        }
    }
}